import { actions } from 'mirrorx'
import api from '../api'

export default {
  name: 'menuModel',
  initialState: {
    allMenus: [],
    grantedMenus: [],
    authList: []
  },
  reducers: {
    // 所有菜单
    setAllMenus (state, data) {
      return Object.assign({}, state, { allMenus: data })
    },
    // 已授权菜单
    setGrantedMenus (state, data) {
      return Object.assign({}, state, { grantedMenus: data })
    },
    setAuthList (state, data) {
      return Object.assign({}, state, { authList: data })
    }
  },
  effects: {
    getAllMenus (type) {
      global.T.ajax({
        url: api.getAllMenus.path + '/platform',
        method: 'get'
      }).then((res) => {
        if (res.code === 0) {
          let data = res.data
          actions.menuModel.setAllMenus(data || [])
        }
      })
    },
    getGrantedMenus (userId) {
      global.T.ajax({
        url: `${api.getGrantedMenus.path}/platform/${userId}`,
        method: 'get'
      }).then((res) => {
        if (res.code === 0) {
          let data = res.data
          if (res.data.length === 0) {
            actions.routing.push({ pathname: '/empty' })
          } else {
            if (data && Array.isArray(data)) {
              data.forEach(item => {
                let { children } = item
                if (children) {
                  let auth = 'view'
                  children.forEach(subItem => {
                    let name = subItem.name
                    name = name.toLowerCase()
                    // 说明菜单具有管理权限
                    if (name === 'management') {
                      auth = 'management'
                    } else {
                      auth = 'view'
                    }
                    return subItem
                  })
                  item.auth = auth
                }
              })
              actions.menuModel.setGrantedMenus(data || [])
            }
          }
        }
      })
    }
  }
}
